package service

import (
	"anban/models"
	"anban/utils"
	"anban/utils/pinyin"
	"fmt"
	"github.com/astaxie/beego/orm"
	"math/rand"
	"net/url"
	"strconv"
	"time"
)

type ClassValue struct {
	Id    int64  `json:"id"`
	Value string `json:"value"`
}

// 获取班级信息
func GetClassInfo(p map[string]interface{}) *models.Class {
	o := orm.NewOrm()
	class := &models.Class{}
	qs := o.QueryTable("Class")
	if _, ok := p["relation"]; ok && p["relation"].(bool) {
		qs = qs.RelatedSel()
	}
	if _, ok := p["id"]; ok {
		qs = qs.Filter("id", p["id"])
	}
	if _, ok := p["name"]; ok {
		qs = qs.Filter("name", p["name"])
	}
	if _, ok := p["status"]; ok {
		qs = qs.Filter("status", p["status"])
	}
	qs.One(class)
	if _, ok := p["convert"]; ok && p["convert"].(bool) {
		if class.Id > 0 {
			class.StatusShow = models.ClassStatus[class.Status]
		}
	}
	if _, ok := p["apiWithStudent"]; ok && p["apiWithStudent"].(bool) {
		param := map[string]interface{}{}
		param["classId"] = class.Id
		param["status"] = 1
		count, studentList := GetStudentList(param)
		class.StudentList = studentList
		class.StudentNum = count
	}
	return class
}

// 添加班级信息
func AddClass(input url.Values) (int64, error) {
	o := orm.NewOrm()
	pinyin.LoadingPYFileName("./static/pinyin.txt")
	class := &models.Class{}
	school := &models.School{}
	if _, ok := input["school_id"]; ok {
		school.Id = utils.Atoi64(input["school_id"][0])
		o.Read(school)
	}
	class.School = school
	schoolPinYin, err := pinyin.To_Py(school.Name, "", pinyin.InitialsInCapitals)
	if err != nil {
		return 0, err
	}
	var sn []rune
	for _, s := range schoolPinYin {
		if s >= 'A' && s <= 'Z' {
			sn = append(sn, s)
		}
		if len(sn) >= 2 {
			break
		}
	}
	n := string(sn) + fmt.Sprintf("%04v", rand.New(rand.NewSource(time.Now().UnixNano())).Int31n(10000))
	count, _ := o.QueryTable("Class").Filter("sn", n).Count()
	for ; count > 0; {
		n = string(sn) + fmt.Sprintf("%04v", rand.New(rand.NewSource(time.Now().UnixNano())).Int31n(10000))
		count, _ = o.QueryTable("Class").Filter("sn", n).Count()
	}
	class.Sn = n
	if _, ok := input["school_id"]; ok {
		class.Name = input["name"][0]
	}
	if _, ok := input["status"]; ok {
		class.Status, _ = strconv.Atoi(input["status"][0])
	}
	return o.Insert(class)
}

// 修改班级信息
func EditClass(input url.Values) (int64, error) {
	o := orm.NewOrm()
	p := orm.Params{}
	for k, v := range input {
		if k == "id" || k == "_xsrf" {
			continue
		}
		p[k] = v[0]
	}
	return o.QueryTable("Class").Filter("id", input["id"][0]).Update(p)
}

// 获取班级列表
func GetClassList(p map[string]interface{}) (int64, []*models.Class) {
	var classList []*models.Class
	o := orm.NewOrm()
	qs := o.QueryTable("Class")
	if _, ok := p["relation"]; ok && p["relation"].(bool) {
		qs = qs.RelatedSel()
	}
	if _, ok := p["userId"]; ok {
		qs = qs.Filter("Users__User__Id", p["userId"])
	}
	if _, ok := p["schoolId"]; ok {
		qs = qs.Filter("school_id", p["schoolId"])
	}
	if _, ok := p["status"]; ok {
		qs = qs.Filter("status", p["status"])
	}
	totalCount, _ := qs.Count()
	curPage, ok := p["curPage"]
	perCount, _ := p["perCount"]
	if ok {
		start := perCount.(int) * (curPage.(int) - 1)
		qs = qs.Limit(perCount, start)
	}
	qs.OrderBy("-id").All(&classList)
	if _, ok := p["convert"]; ok && p["convert"].(bool) {
		for _, class := range classList {
			class.StatusShow = models.ClassStatus[class.Status]
		}
	}
	if _, ok := p["apiWithStudent"]; ok && p["apiWithStudent"].(bool) {
		for _, class := range classList {
			param := map[string]interface{}{}
			param["classId"] = class.Id
			param["status"] = 1
			count, studentList := GetStudentList(param)
			class.StudentList = studentList
			class.StudentNum = count
		}
	}
	if _, ok := p["withStudent"]; ok && p["withStudent"].(bool) {
		for _, class := range classList {
			param := map[string]interface{}{}
			param["classId"] = class.Id
			param["status"] = 1
			count, studentList := GetStudentList(param)
			class.StudentList = studentList
			class.StudentNum = count
		}
	}
	return totalCount, classList
}

func GetClassListValues(classList []*models.Class) []*ClassValue {
	data := []*ClassValue{}
	for _, class := range classList {
		classVal := &ClassValue{
			Id:    class.Id,
			Value: class.Name,
		}
		data = append(data, classVal)
	}
	return data
}
